package com.zmn.plat.admin.controller.product.tariff;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.plat.admin.controller.PlatBaseController;
import com.zmn.plat.business.interfaces.product.tariff.ProductTariffBService;
import com.zmn.plat.manager.dictionary.ProductDict;
import com.zmn.plat.model.entity.product.ServProduct;
import com.zmn.plat.model.entity.product.tariff.ProductTariff;
import com.zmn.plat.model.entity.product.tariff.ProductTariffQuery;
import com.zmn.plat.model.entity.product.tariff.group.ProductTariffGroupQuery;
import com.zmn.plat.model.entity.service.group.ServiceGroup;
import com.zmn.plat.model.entity.service.group.ServiceGroupQuery;
import com.zmn.plat.model.entity.service.item.ServiceItem;
import com.zmn.plat.model.entity.service.item.ServiceItemQuery;
import com.zmn.plat.model.entity.service.tariff.ServiceTariff;
import com.zmn.plat.model.vo.product.tariff.ProductTariffVO;
import com.zmn.plat.model.vo.product.tariff.group.ProductTariffGroupVO;
import com.zmn.plat.services.interfaces.category.BaseCategoryService;
import com.zmn.plat.services.interfaces.channel.ChannelService;
import com.zmn.plat.services.interfaces.product.ServProductService;
import com.zmn.plat.services.interfaces.product.tariff.ProductTariffService;
import com.zmn.plat.services.interfaces.product.tariff.group.ProductTariffGroupService;
import com.zmn.plat.services.interfaces.servcategory.ServAssCategoryService;
import com.zmn.plat.services.interfaces.servcategory.ServCategoryService;
import com.zmn.plat.services.interfaces.service.group.ServiceGroupService;
import com.zmn.plat.services.interfaces.service.item.ServiceItemService;
import com.zmn.plat.services.interfaces.service.tariff.ServiceTariffService;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 产品故障价格表，每个产品价格表一条数据，配置价格表说明、状态等
 *
 * @author linfeng
 * @since 2019-11-21 18:57:24
 */
public class ProductTariffBaseController extends PlatBaseController {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    protected ProductTariffService productFaultTariffService;

    @Resource
    protected ServAssCategoryService servAssCategoryService;

    @Resource
    protected ChannelService channelService;

    @Resource
    protected ServCategoryService servCategoryService;

    @Resource
    protected BaseCategoryService baseCategoryService;

    @Resource
    protected ServiceTariffService faultTariffService;

    @Resource
    protected ServProductService servProductService;

    @Resource
    protected ServiceGroupService faultGroupService;

    @Resource
    protected ServiceItemService faultItemService;

    @Resource
    protected ProductTariffGroupService productFaultGroupService;

    @Resource
    protected ProductTariffBService productFaultTariffBService;

    /**
     * 功能描述 :跳转到添加价格表页面
     *
     * @param mv
     * @param productId
     * @param bizType
     * @param tariffId
     * @return void
     * @author linfeng
     * @modifier
     * @since 2019/11/27
     */
    @SuppressWarnings("Duplicates")
    void baseAddEditProductPrice(ModelAndView mv, Integer productId, Integer tariffId, Integer bizType) {
        ServiceTariff faultTariff = faultTariffService.findByKey(tariffId);
        List<ServiceGroup> faultGroup = getFaultGroup(productId, tariffId);
        // 过滤出启用状态的分组
        faultGroup = faultGroup.stream().filter(e -> e.getStatus().equals(GlobalConsts.YES)).collect(Collectors.toList());
        // 设置分组默认状态为未选中
        faultGroup.forEach(e -> e.setStatus(GlobalConsts.NO));

        ProductTariffGroupQuery productFaultGroupQuery = new ProductTariffGroupQuery();
        productFaultGroupQuery.setTariffId(tariffId);
        productFaultGroupQuery.setProductId(productId);
        // productFaultGroupQuery.setKeepType(bizType);
        List<ProductTariffGroupVO> productFaultGroupVOList = productFaultGroupService.listByQuery(productFaultGroupQuery);

        ProductTariffQuery productFaultTariffQuery = new ProductTariffQuery();
        productFaultTariffQuery.setProductId(productId);
        productFaultTariffQuery.setTariffId(tariffId);
        List<ProductTariffVO> productFaultTariffs = productFaultTariffService.listByQuery(productFaultTariffQuery);
        ProductTariff productFaultTariff = new ProductTariff();
        if (productFaultTariffs != null && productFaultTariffs.size() > 0) {
            BeanUtils.copyProperties(productFaultTariffs.get(0), productFaultTariff);
        }
        mv.addObject("productFaultTariff", productFaultTariff);

        List<Integer> relationGroupIds = productFaultGroupVOList.stream().map(e -> e.getGroupId()).collect(Collectors.toList());
        faultGroup.forEach(group -> {
            if (relationGroupIds.contains(group.getGroupId())) {
                group.setStatus(GlobalConsts.YES);
            } else {
                group.setStatus(GlobalConsts.NO);
            }
        });

        ServProduct servProduct = productId > 0 ? servProductService.findByKey(productId) : new ServProduct();
        mv.addObject("servProductVO", servProduct);
        mv.addObject("productName", servProduct.getName());
        mv.addObject("faultTariff", faultTariff);
        mv.addObject("faultGroup", faultGroup);
        mv.addObject("productId", productId);
        mv.addObject("tariffId", tariffId);
        mv.addObject("bizType", faultTariff.getBizType());
        // if (bizType.intValue() == ProductConsts.BIZ_TYPE_C){
        // mv.addObject("flag", 6);
        // } else {
        // mv.addObject("flag", 7);
        // }
    }

    /**
     * 描述: 获取服务组组合
     *
     * @param productId 产品价格表
     * @param tariffId  价格表id
     * @return java.util.List<com.zmn.plat.model.entity.service.group.ServiceGroup>
     * @author linfeng
     * @since 2019/11/28
     **/
    List<ServiceGroup> getFaultGroup(@NotNull Integer productId, @NotNull Integer tariffId) {

        ServProduct servProduct = servProductService.findByKey(productId);
        ServiceGroupQuery query = new ServiceGroupQuery();
        query.setServCategId(servProduct.getServCategId());
        query.setCategOneId(servProduct.getCategOneId());
        query.setTariffId(tariffId);

        return Optional.ofNullable(faultGroupService.listByQuery(query)).orElse(Collections.emptyList());
    }

    /**
     * 描述: 添加产品价格表
     *
     * @param productFaultTariffVO 产品价格表
     * @return com.zmn.common.dto2.ResponseDTO
     * @author linfeng
     * @since 20191127
     **/
    @SuppressWarnings("Duplicates")
    ResponseDTO baseSaveProductPriceTable(ProductTariffVO productFaultTariffVO) {
        ServiceTariff faultTariff = faultTariffService.findByKey(productFaultTariffVO.getTariffId());
        if (Objects.equals(productFaultTariffVO.getStatus(), GlobalConsts.YES)
                && Objects.equals(faultTariff.getStatus(), GlobalConsts.NO)) {
            return ResponseDTO.fail("请先在价格表管理页面启用“" + faultTariff.getTariffName() + "”");
        }
        ProductTariffQuery query = new ProductTariffQuery();
        query.setProductId(productFaultTariffVO.getProductId());
        query.setTariffId(productFaultTariffVO.getTariffId());
        // 检查选择的服务分组是否存在多个默认项
        List<Integer> groupList = productFaultTariffVO.getGroupIds();
        ServiceItemQuery faultItemQuery = new ServiceItemQuery();
        faultItemQuery.setGroupIds(groupList);
        List<ServiceItem> selectedServiceItems = faultItemService.listByQuery(faultItemQuery);
        List<ServiceItem> defaultItems =
                selectedServiceItems.stream().filter(e -> e.getGeneral().equals(ProductDict.DEFAULT_ITEM_YES)).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(defaultItems) && defaultItems.size() > 1) {
            StringBuilder stringBuilder = new StringBuilder();
            defaultItems.forEach(e -> {
                if (stringBuilder.indexOf(e.getGroupName()) == -1) {
                    stringBuilder.append(e.getGroupName()).append("<").append(e.getGroupId()).append(">").append(",");
                }
            });
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            return ResponseDTO.fail("一个价格表里面最多有一个默认项,而服务分组" + stringBuilder.toString() + "均存在默认项，不能保存！");
        }

        if (productFaultTariffVO.getStatus().equals(GlobalConsts.NO) && productFaultTariffVO.getGeneral().equals(GlobalConsts.YES)) {
            return ResponseDTO.fail("默认价格表不能被停用！");
        }

        long count = Optional.ofNullable(productFaultTariffService.listByQuery(query)).orElse(Collections.emptyList()).size();

        query = new ProductTariffQuery();
        query.setBizType(productFaultTariffVO.getBizType());
        query.setProductId(productFaultTariffVO.getProductId());
        query.setTariffType(faultTariff.getTariffType());
        query.setGeneral(GlobalConsts.YES);

        List<ProductTariffVO> innerList = productFaultTariffService.listByQuery(query);
        String bizType = com.zmn.plat.common.dictionary.ProductDict.getBizTypeCNENName(faultTariff.getBizType());

        String tariffType = "服务价格";
        if (Objects.equals(faultTariff.getTariffType(), ProductDict.TRIFF_TYPE_SERVICE)) {
            tariffType = "服务价格";
        }
        if (Objects.equals(faultTariff.getTariffType(), ProductDict.TRIFF_TYPE_TARIFF)) {
            tariffType = "计价器价格";
        }
        if (Objects.equals(faultTariff.getTariffType(), ProductDict.TRIFF_TYPE_ADVANCE)) {
            tariffType = "提前支付价格";
        }
        if (!CollectionUtils.isEmpty(innerList)) {
            if (innerList.size() > 1 || (!innerList.get(0).getTariffId().equals(productFaultTariffVO.getTariffId())
                    && productFaultTariffVO.getGeneral().equals(GlobalConsts.YES))) {
                return ResponseDTO.fail(String.format("%s的%s最多一个默认价格表", bizType, tariffType));
            }
        }
        if (count > 0) {
            productFaultTariffBService.modifyProductFaultTariff(productFaultTariffVO, getMcStaff());
        } else {
            productFaultTariffBService.addProductFaultTariff(productFaultTariffVO, getMcStaff());
        }

        return ResponseDTO.success(productFaultTariffVO.getProductId(), "操作成功！");
    }
}
